class Solution {
    int n, m;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int prev = 0;
    int ret = 0, path = 1;
public:
    void dfs(vector<vector<int> >& matrix, int i, int j)
    {
        ret = max(ret, path);

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < n && y >= 0 && y < m && prev < matrix[x][y])
            {
                int t = prev;
                prev = matrix[x][y];
                path++;
                dfs(matrix, x, y);
                path--;
                prev = t;
            }
        }
    }

    int solve(vector<vector<int> >& matrix) {
        n = matrix.size(), m = matrix[0].size();
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                prev = matrix[i][j];
                dfs(matrix, i, j);
            }
        }

        return ret;
    }
};
